package com.meixiang.activity.account.manager;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.adapter.AddressManageAdapter;
import com.meixiang.entity.account.AddressListEntity;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.TitleView;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 地址管理
 * author：wangzuzhen
 */
public class AddressManageActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {
    @Bind(R.id.title)
    TitleView title;
    @Bind(R.id.swipe_target)
    RecyclerView mSwipeTarget;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;

    public Map<Integer, Boolean> isSelected;
    private List<Object> selectedData = new ArrayList<>();//已选

    private boolean isDownPull;
    private List<AddressListEntity> mAddressList;
    private AddressManageAdapter mAdapter;
    private Activity mActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_address_manage);
        ButterKnife.bind(this);
        mActivity = AddressManageActivity.this;
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initTitle() {
        title.setTitle(R.string.address_manage);
        title.setLeftImageButton(R.mipmap.back);
        title.showLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });
        title.setRightTextButton(R.string.add);
        title.showRightButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, AddressActivity.class);
                intent.putExtra("status", "2");
                startActivity(intent);
            }
        });
    }

    @Override
    protected void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mSwipeTarget.setLayoutManager(linearLayoutManager);

        mAdapter = new AddressManageAdapter(this);
        mSwipeTarget.setAdapter(mAdapter);

        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);


        //RecyclerView滑到底部自动加载更多
        mSwipeTarget.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(recyclerView, 1)) {
                        mRefresh.setLoadingMore(true);
                    }
                }
            }
        });


        mAdapter.setOnAddressItemClickListener(new AddressManageAdapter.onAddressItemClickListener() {
            @Override
            public void onSetDefaultItemClick(View v, int position) {

                boolean isChecked = !isSelected.get(position);
                for (Integer flag : isSelected.keySet()) {
                    isSelected.put(flag, false);
                }
                isSelected.put(position, isChecked);
                mAdapter.notifyDataSetChanged();
                selectedData.clear();
                if (isChecked) {
                    selectedData.add(mAddressList.get(position));
                }
                setDefault(position);//设置默认接口
            }

            @Override
            public void onDeleteItemClick(View v, int position) {
                deleteAddress(position);
            }
        });
    }

    @Override
    protected void setData() {

    }

    //获取数据
    private void getAddressData() {
        HttpParams params = new HttpParams();
        HttpUtils.post(Config.MY_ADDRESS_INDEX, params, new HttpCallBack(AddressManageActivity.this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if (isDownPull) {
                    mAdapter.clearData();
                }
                mAddressList = AbJsonUtil.fromJson(result.optJSONArray("list").toString(), new TypeToken<ArrayList<AddressListEntity>>() {
                });
                if (mAddressList == null || mAddressList.size() == 0) {
                    status.showNoData("暂无数据");
                } else {
                    status.removeView();

                    setSelected();
                    if ((mAddressList.size() - 1) == 0 && !mAddressList.get(0).getIsDefault().equals("1")) {//默认
                        setDefault(0);
                    }
                    mAdapter.addData(mAddressList);
                    mAdapter.notifyDataSetChanged();
                }


            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(context, message);
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                onCompleRefresh();
            }
        });
    }

    private void setSelected() {
        if (mAddressList == null || mAddressList.size() == 0)
            return;

        if (isSelected != null)
            isSelected = null;
        isSelected = new HashMap<Integer, Boolean>();
        for (int i = 0; i < mAddressList.size(); i++) {
            isSelected.put(i, false);
        }
        // 清除已经选择的项
        if (selectedData.size() > 0) {
            selectedData.clear();
        }
    }

    /**
     * 设置默认
     */
    private void setDefault(final int position) {
        HttpParams params = new HttpParams();
        params.put("addressId", mAddressList.get(position).getAddressId());
        HttpUtils.post(Config.MY_ADDRESS_SET_DEFAULT, params, new HttpCallBack(activity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                if ("0".equals(code)) {
                    Tool.showTextToast(activity, "设置默认地址成功");

                    AddressListEntity mEntity = mAddressList.get(position);
                    mEntity.setIsDefault("1");
                    mAdapter.notifyItemChanged(position);

                    mRefresh.setRefreshing(true);
                } else {
                    Tool.showTextToast(activity, message);
                }
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(activity, message);
            }
        });
    }

    /**
     * 删除地址
     */
    private void deleteAddress(final int position) {
        HttpParams params = new HttpParams();
        params.put("addressId", mAddressList.get(position).getAddressId());
        HttpUtils.post(Config.MY_ADDRESS_DELETE, params, new HttpCallBack(activity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(activity, "删除成功");
                mAdapter.removeData(position);
                mAdapter.notifyItemRemoved(position);
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(activity, message);
            }
        });

    }

    @Override
    public void onClick(View v) {
    }


    @Override
    public void onLoadMore() {
        // TODO 加载更多
        isDownPull = false;
        mRefresh.post(new Runnable() {
            @Override
            public void run() {
                mRefresh.setLoadingMore(false);
            }
        });
    }

    @Override
    public void onRefresh() {
        // TODO 刷新
        isDownPull = true;
        getAddressData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mRefresh.post(new Runnable() {
            @Override
            public void run() {
                mRefresh.setRefreshing(true);
            }
        });

    }

    private void onCompleRefresh() {
        mRefresh.setRefreshing(false);
        mRefresh.setLoadingMore(false);
    }

}



